﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using SKYPE4COMLib;
using PLAYXPERT.Windows;
using BackLib;
using BackLib.Networking;

namespace SkypePXP
{
    public partial class ShareForm : PXPForm
    {
        User user;
        DirectCapture Cap;
        TCP Tcp;

        // Threads
        Thread SendQueThread;

        // Image Lists
        List<Image> InQue = new List<Image>();
        List<byte[]> OutQue = new List<byte[]>();
        bool Sent = false;

        public ShareForm(PLAYXPERT.Interfaces.ICore iCore, User user, DirectCapture Cap)
        {
            InitializeComponent();

            // Initialize Form
            iCore.GetSkinEngine().ApplySkin(this);
            this.Cap = Cap;
            this.user = user;
            this.Text = "Game Share - " + user.Handle;
        }

        #region Event Handlers

        void Handler_Disconnected()
        {
            SendQueThread.Suspend();
        }

        void User_ConnectionStatusChanged(bool hosting, bool connected)
        {
            if (connected)
            {
                SendQueThread = new Thread(SendQue);
                SendQueThread.Start();
            }
            else
            {
                if (SendQueThread != null)
                    SendQueThread.Suspend();
            }
        }

        void Handler_SentPacket(PacketType packetType, int size, int time, int rate)
        {
            Sent = true;
        }

        void Handler_ReceivedScreenshot(byte[] buffer)
        {
            // Get Image
            InQue.Add(Image.FromStream(new MemoryStream(buffer)));
            imageList1.Images.Add(InQue[InQue.Count - 1].GetThumbnailImage(64, 64, null, IntPtr.Zero));

            // Add to ListView
            ListViewItem item = new ListViewItem();
            item.ImageIndex = imageList1.Images.Count - 1;
            listView1.Items.Add(item);

            // Kick Start
            if (InQue.Count == 1)
                pictureBox1.Image = InQue[0];
        }

        #endregion

        #region Form Code

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            pictureBox1.Image = InQue[listView1.SelectedItems[0].Index];
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            byte[] Buffer = Cap.GetBytes(Format.Jpeg, 0);
        }

        #endregion

        public void ScreenShotTaken()
        {
            // Add to the Que
            OutQue.Add(Cap.GetBytes(Format.Jpeg, 0));
        }

        public void SendQue()
        {
            while (true)
            {
                for (int i = 0; i < OutQue.Count; i++)
                    SendQueItem();
            }
        }

        public void SendQueItem()
        {
            if (OutQue.Count > 0)
            {
                // Send the Buffer
                Tcp.User.SendData(OutQue[0]);

                // Wait for Confirmation
                DateTime Start = DateTime.Now;
                while (Sent != true)
                {
                    // SOS
                    TimeSpan t = DateTime.Now - Start;
                    if (t.Seconds >= 30)
                    {
                        // BLARG!
                        break;
                    }

                    System.Windows.Forms.Application.DoEvents();
                }

                // Remove from Que
                if (Sent)
                    OutQue.RemoveAt(0);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Initialize TCP
            Tcp = new TCP(checkBox1.Checked, textBox1.Text, 3000);
            Tcp.User.Handler.ReceivedScreenshot += new TCPHandling.ReceivedScreenshotHandler(Handler_ReceivedScreenshot);
            Tcp.User.Handler.SentPacket += new TCPHandling.SentPacketHandler(Handler_SentPacket);
            Tcp.User.ConnectionStatusChanged += new ITCPUser.ConnectionStatusChangedHandler(User_ConnectionStatusChanged);
            Tcp.User.Handler.Disconnected += new TCPHandling.DisconnectedHandler(Handler_Disconnected);

            // Connect
            Tcp.Connect();
        }
    }
}
